<?php
/**
 * Created by PhpStorm.
 * User: luzy
 * Date: 2018/7/18
 * Time: 下午8:03
 */

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
require_once __DIR__.'/../third_party/PhpSpreadExcel/vendor/autoload.php';

class Excel_model extends Base_Model
{
    private $_sheet;
    public function __construct()
    {
        parent::__construct();
    }
    
    public function createSheet()
    {
        $this->_sheet = new Spreadsheet();
    }
    
    public function setSheetValue($sheetindex,$title,$data)
    {
        $cols = array('A','B','C','D','E','F','G','H','I','J',
            'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        $this->_sheet->setActiveSheetIndex($sheetindex);
        foreach ($data as $i=>$row){
            $rowindex = $i+1;
            foreach ($row as $j=>$cell){
                $this->_sheet->getActiveSheet()->setCellValue($cols[$j].$rowindex, $cell);
            }
        }
        $this->_sheet->getActiveSheet()->setTitle($title);
    }

    public function downloadExcel($filename)
    {
        // Redirect output to a client’s web browser (Xls)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($this->_sheet, 'Xlsx');
        $writer->save('php://output');
    }

}